#include "KDM2EventAction.hh"
#include "KDM2HitsCollection.hh"
#include "KDM2Hit.hh"
#include "KDM2Globals.hh"
#include "G4HCofThisEvent.hh"
#include "G4Event.hh"
#include "G4SDManager.hh"
#include "G4ThreeVector.hh"
#include "TH3D.h"
#include "TFile.h"
#include "TTree.h"
#include "TBranch.h"
#include <sstream>
#include <iostream>
using namespace std;

KDM2EventAction::KDM2EventAction() {
	;
}

KDM2EventAction::~KDM2EventAction() {
	;
}

void KDM2EventAction::BeginOfEventAction(const G4Event*) {
	BHVeto = false;
	frontVeto = false;
	rearVeto = false;
	sideVeto = false;
	barrelVeto = false;
}

void KDM2EventAction::EndOfEventAction(const G4Event* event) {
	G4HCofThisEvent* hcc = event->GetHCofThisEvent();
	KDM2HitsCollection* hc = (KDM2HitsCollection*) (hcc->GetHC(0));
	size_t size = hc->GetSize();

	int kaonNumber = eventNum / maxPhotons;
	int photonNumber = eventNum % maxPhotons;
	std::stringstream ss;
	ss << "eventNumber" << kaonNumber;
	G4String name = ss.str();

	if (photonNumber == 0) {
		tree = new TTree(name, name);
		energyBranch = tree->Branch("energy", &photonEnergy, "energy/D");
		BHVetoBranch = tree->Branch("BHVeto", &BHVeto, "veto/O");
		frontVetoBranch = tree->Branch("frontVeto", &frontVeto, "veto/O");
		rearVetoBranch = tree->Branch("rearVeto", &rearVeto, "veto/O");
		sideVetoBranch = tree->Branch("sideVeto", &sideVeto, "veto/O");
		barrelVetoBranch = tree->Branch("barrelVeto", &barrelVeto, "veto/O");
	}

	energyBranch->Fill();
	BHVetoBranch->Fill();
	frontVetoBranch->Fill();
	rearVetoBranch->Fill();
	sideVetoBranch->Fill();
	barrelVetoBranch->Fill();

	std::stringstream ss2;
	ss2 << "photonNumber" << photonNumber;
	name = ss2.str();
	dataForm* data = new dataForm;
	TBranch* dataBranch = tree->Branch(name, &(*data).energy, "energy/D:time:x:y:z");
	ss2 << "OEV";
	name = ss2.str();
	TBranch* OEVBranch = tree->Branch(name, &(*data).energy, "energy/D:time:x:y:z");
	for (size_t i = 0; i < size; i++) {
		TBranch* branch = dataBranch;
		KDM2Hit* hit = (KDM2Hit*) hc->GetHit(i);
		if (hit->getVeto())
			branch = OEVBranch;
		(*data).energy = hit->GetEnergy();
		(*data).time = hit->GetTime();
		G4ThreeVector pos = hit->GetPosition();
		(*data).x = pos.x();
		(*data).y = pos.y();
		(*data).z = pos.z();
		branch->Fill();
	}

	if (photonNumber == (maxPhotons - 1)) {
		tree->Write();
		tree->Delete();
	}
	delete data;
}
